package com.cch.demo.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cch.demo.sys.domain.Permission;
import com.cch.demo.sys.domain.Role;
import com.cch.demo.sys.domain.User;
import com.cch.demo.sys.service.PermissionService;
import com.cch.demo.sys.service.RoleService;
import com.cch.demo.sys.service.impl.RoleServiceImpl;
import com.cch.demo.sys.util.*;
import com.cch.demo.sys.vo.RoleVo;
import com.cch.demo.sys.vo.RoleVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 华哥
 * @since 2020-03-08
 */
@RestController
@RequestMapping("role")
public class RoleController {

    @Resource
    private RoleService roleServiceImpl;

    @Resource
    private PermissionService permissionServiceImpl;

    @RequestMapping("/loadAllRole")
    public DataGridView loadAllRole(RoleVo roleVo){
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(roleVo.getName()),"name",roleVo.getName());
        queryWrapper.like(StringUtils.isNotBlank(roleVo.getRemark()),"remark",roleVo.getRemark());
        queryWrapper.eq(roleVo.getAvailable()!=null,"available",roleVo.getAvailable());

        queryWrapper.orderByDesc("createtime");
        IPage<Role> page = new Page<>(roleVo.getPage(),roleVo.getLimit());
        roleServiceImpl.page(page,queryWrapper);
        return new DataGridView(page.getTotal(),page.getRecords());
    }

    @RequestMapping("addRole")
    public ResultObj addRole(RoleVo roleVo){
        try{
            roleVo.setCreatetime(new Date());
            roleServiceImpl.save(roleVo);
            return ResultObj.ADD_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }

    @RequestMapping("updateRole")
    public ResultObj updateRole(RoleVo roleVo){
        try{
            QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id",roleVo.getId());

            roleVo.setCreatetime(new Date());
            roleServiceImpl.update(roleVo,queryWrapper);
            return ResultObj.UPDATE_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }

    @RequestMapping("deleteRole")
    public ResultObj deleteRole(Integer id){
        try{
            roleServiceImpl.removeById(id);
            return ResultObj.DELETE_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }

    /**
     * 根据角色ID加载菜单和权限的树的json串
     */
    @RequestMapping("initPermissionByRoleId")
    public DataGridView initPermissionByRoleId(Integer rid){
        //查询所有权限和菜单
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("available", Constast.AVAILABLE_TRUE);//查询有用的
        List<Permission> allPermissions = permissionServiceImpl.list(queryWrapper);

        /**
         * 1,根据角色ID查询当前角色拥有的所有的权限或菜单ID
         * 2,根据查询出来的菜单ID查询权限和菜单数据
         */
        List<Integer> pids = roleServiceImpl.queryRolePermissionByRid(rid);
        List<Permission> usePermissions = null;
        if(pids.size()>0&&pids!=null){
            //根据查询出来的菜单ID查询权限和菜单数据
            queryWrapper.in("id",pids);
            usePermissions = permissionServiceImpl.list(queryWrapper);
        }else{
            //如果什么都没有
            usePermissions = new ArrayList<>();
        }

        //构造 List<TreeNode>
        List<TreeNode> list = new ArrayList<>();
        for(Permission p1 : allPermissions){
            String checkArr = "0";
            for (Permission p2:usePermissions){
                if(p2.getId() == p1.getId()){
                    checkArr = "1";
                    break;
                }
            }
            Boolean spread = (p1.getOpen()==null||p1.getOpen()==0)?false:true;//p1.getOpen()==null数据库中大多为null
            list.add(new TreeNode(p1.getId(),p1.getPid(),p1.getTitle(),spread,checkArr));
        }

        return new DataGridView(list);
    }

    /**
     * 保存角色和菜单权限之间的关系
     * @param rid
     * @param ids
     * @return
     */
    @RequestMapping("saveRolePermission")
    public ResultObj saveRolePermission(Integer rid,Integer[] ids){
        try{
            roleServiceImpl.saveRolePermission(rid,ids);
            return  ResultObj.DISPATCH_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return  ResultObj.DISPATCH_ERROR;
        }
    }

    @RequestMapping("saveRoleUser")
    public ResultObj saveRoleUser(Integer uid,Integer[] ids){
        try{
            roleServiceImpl.saveRoleUser(uid,ids);
            return  ResultObj.DISPATCH_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return  ResultObj.DISPATCH_ERROR;
        }
    }

}

